package service;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class Main {
    public static void main(String[] args) {
        IProductService service = (IProductService) rpc(IProductService.class);
        System.out.println(service);
    }

    public static Object rpc(final Class clazz) {
        return Proxy.newProxyInstance(clazz.getClassLoader(),
                new Class[]{clazz}, (proxy, method, args) -> {
                    Socket socket = new Socket("127.0.0.1", 8888);
                    //api
                    String clazzName = clazz.getName();
                    String methodName = method.getName();
                    Class[] parameterTypes = method.getParameterTypes();
                    // output
                    ObjectOutputStream is = new ObjectOutputStream(socket.getOutputStream());
                    is.writeUTF(clazzName);
                    is.writeUTF(methodName);
                    is.writeObject(parameterTypes);
                    is.writeObject(args);
                    is.flush();
                    // input
                    ObjectInputStream os = new ObjectInputStream(socket.getInputStream());
                    Object object = os.readObject();
                    is.close();
                    os.close();
                    socket.close();

                    return object;
                });
    }
}
